package com.jushu.storbox.service;

import java.util.List;

import android.annotation.SuppressLint;
import android.app.IntentService;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;

import com.jushu.storbox.R;
import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.filesystem.FileManagerFactory;
import com.jushu.storbox.filesystem.iFileManager;
import com.jushu.storbox.network.WifiController;
import com.jushu.storbox.util.DataUploadUtil;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.view.dialog.ExceptionPrompt;
import com.huawei.sharedrive.sdk.android.exception.ClientException;
import com.huawei.sharedrive.sdk.android.model.request.FolderCreateRequest;
import com.huawei.sharedrive.sdk.android.modelV2.request.FolderSearchRequestV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.FileInfoResponseV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.FolderListResponseV2;

@SuppressLint("HandlerLeak")
public class UploadService extends IntentService
{
    private ICloudDriveService shareDriveService;
    
    private List<FileFolderInfo> moveList = null;
    
    private static final String LOG = "UploadService";
    
    private FileFolderInfo folder;
    
    private boolean isUploadInputStrem = false;
    
    private String uploadFileUrl;
    
    private NotificationCompat.Builder mNotification;
    
    private NotificationManager mNotificationManager;
    
    // private InputStream uploadInputStream;
    private int notificationID;
    
    private String folderID;
    
    private String noteFolderID = "";
    
    private iFileManager mdmTools = null;
    
    private Bundle bundle;
    
    @SuppressWarnings("unused")
    private final IBinder binder = new CenterUploadServiceServiceBinder();
    
    public class CenterUploadServiceServiceBinder extends Binder
    {
        public UploadService getService()
        {
            return UploadService.this;
        }
    }
    
    @Override
    public void onCreate()
    {
        super.onCreate();
    }
    
    public UploadService()
    {
        super(LOG);
        // TODO Auto-generated constructor stub
    }
    
    @Override
    public IBinder onBind(Intent intent)
    {
        LogUtil.i(LOG, "onBind()...");
        // return binder;
        return super.onBind(intent);
    }
    
    @Override
    public void onStart(Intent intent, int startId)
    {
        super.onStart(intent, startId);
    }
    
    private ServiceConnection serviceConnection = new ServiceConnection()
    {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service)
        {
            shareDriveService = ((CloudDriveService.CenterShareDriveServiceServiceBinder) service).getService();
            LogUtil.i(LOG, "onServiceConnected | uploadFileUrl:" + uploadFileUrl);
            mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            int struts = new WifiController(UploadService.this).getNetWord();
            if (struts == 0)
            {
                LogUtil.i(LOG, "onServiceConnected | struts:" + struts + " :"
                    + UploadService.this.getResources().getString(R.string.allfile_notwork_obstructed));
                Toast.makeText(UploadService.this,
                    UploadService.this.getResources().getString(R.string.allfile_notwork_obstructed),
                    Toast.LENGTH_LONG).show();
            }
            else
            {
                LogUtil.i(LOG, "onServiceConnected | struts:" + struts + " :start AsyloginVerification...");
                new AsyloginVerification().execute();
            }
        }
        
        @Override
        public void onServiceDisconnected(ComponentName name)
        {
            LogUtil.e(LOG, "onServiceDisconnected");
        }
    };
    
    private void uploadData()
    {
        LogUtil.i(LOG, "uploadDataServer...");
        notificationID = ClientConfig.NOTIFICATION_ID += 1;
        if (isUploadInputStrem)
        {
            uploadInputStram(uploadFileUrl, "EmailAttachment", "0", 1);
        }
        else
        {
            // uploadShareFile();
            DataUploadUtil dataUploadTools = new DataUploadUtil(UploadService.this, shareDriveService);
            dataUploadTools.uploadShareFile(folderID, uploadFileUrl, handler);
        }
    }
    
    private class AsyloginVerification extends AsyncTask<Integer, Integer, Integer>
    {
        Handler handler = new Handler()
        {
            @Override
            public void handleMessage(Message msg)
            {
                switch (msg.what)
                {
                    case 1:
                        LogUtil.i(LOG, "AsyloginVerification handleMessage success...");
                        uploadFileUrl = bundle.getString("uploadFileUrl");
                        if (bundle.getString("upload_inputstrem") != null)
                        {
                            isUploadInputStrem = true;
                        }
                        else
                        {
                            isUploadInputStrem = false;
                            folderID = bundle.getString("file_parent_directory_id");
                        }
                        uploadData();
                        break;
                    default:
                        LogUtil.i(LOG, "AsyloginVerification Exception...");
                        ExceptionPrompt.showException(msg.what, UploadService.this);
                        break;
                }
                super.handleMessage(msg);
            }
        };
        
        @Override
        protected Integer doInBackground(Integer... arg0)
        {
            LogUtil.i(LOG, "AsyloginVerification doInBackground...");
            shareDriveService.loginBackGround(handler);
            return null;
        }
    }
    
    private void uploadInputStram(final String fileURl, final String folderName, final String folderID,
        final int uploadPage)
    {
        LogUtil.i(LOG, "uploadInputStram:" + fileURl);
        //
        mdmTools = FileManagerFactory.getFileManager(UploadService.this);
        //
        final FolderCreateRequest request = new FolderCreateRequest();
        request.setName(folderName);
        request.setParent(folderID);
        folder = null;
        folderResponse = null;
        new Thread(new Runnable()
        {
            public void run()
            {
                try
                {
                	String ownerId = ShareDriveApplication.getInstance().getWnerID();
                    if (uploadPage == 1)
                    {
                        LogUtil.i(LOG, "uploadFile:uploadPage == 2");
                        try
                        {
                            if (null != shareDriveService)
                                srequest = new FolderSearchRequestV2();
                            srequest.setName(folderName);
                            srequest.setOwnerID(folderID);
                            folderResponse = shareDriveService.searchFolder(srequest);
                            if (folderResponse != null)
                            {
                                noteFolderID = folder.getId();
                                uploadInputStram(uploadFileUrl,
                                    mdmTools.getParentFolderName(fileURl),
                                    folder.getId(),
                                    2);
                                return;
                            }
                            else
                            {
								folder = shareDriveService.createFolder(UploadService.this, ownerId , request);
                            }
                        }
                        catch (ClientException e1)
                        {
                            e1.printStackTrace();
                            LogUtil.e(LOG,
                                "uploadFile:uploadPage ==2, create file fail:" + e1.getLocalizedMessage());
                            
                        }
                        if (folder == null)
                        {
                            LogUtil.e(LOG, "uploadFile:uploadPage == 2, create file get floder is null");
                            if (null != shareDriveService)
                                moveList = shareDriveService.getMoveFolderList(
                                	ownerId,
                                	folderID,
                                    "DESC",
                                    1000,
                                    0,
                                    "modifiedAt");
                            if (moveList.size() > 0)
                            {
                                LogUtil.i(LOG,
                                    "uploadFile:uploadPage == 2, get moveList size:" + moveList.size());
                                for (FileFolderInfo fileFolderInfo : moveList)
                                {
                                    if (fileFolderInfo.getName().equals(folderName)
                                        && fileFolderInfo.getIsFile() == 0)
                                    {
                                        noteFolderID = fileFolderInfo.getId();
                                        uploadInputStram(uploadFileUrl,
                                            mdmTools.getFileName(fileURl),
                                            fileFolderInfo.getId(),
                                            2);
                                    }
                                }
                            }
                            else
                            {
                                LogUtil.i(LOG, "uploadFile:uploadPage == 2, get moveList size <=0...");
                            }
                        }
                        else
                        {
                            LogUtil.e(LOG, "uploadFile:uploadPage == 2, create file get floder is exist...");
                            noteFolderID = folder.getId();
                            uploadInputStram(uploadFileUrl,
                                mdmTools.getParentFolderName(fileURl),
                                folder.getId(),
                                2);
                        }
                    }
                    else if (uploadPage == 2)
                    {
                        LogUtil.i(LOG, "uploadFile:uploadPage == 3");
                        // upload(noteFolderID,fileURl);
                        DataUploadUtil dataUploadTools = new DataUploadUtil(UploadService.this,
                            shareDriveService);
                        dataUploadTools.uploadStream(noteFolderID, uploadFileUrl, handler);
                    }
                }
                catch (Exception e)
                {
                    LogUtil.e(LOG, "uploadInputStram fail message:" + e.getLocalizedMessage());
                    e.printStackTrace();
                }
            }
        }).start();
    }
    
   
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case 1:
                    
                    break;
                case 3:// file stream
                    LogUtil.i(LOG, "UploadService upload mdm stream success handler...");
                    String fileUrl1 = String.valueOf(msg.obj);
                    //
                    String name1 = "";
                    if (null != fileUrl1 && !"".equals(fileUrl1))
                    {
                        LogUtil.i(LOG, "UploadService upload mdm stream success handler start delete file...");
                        iFileManager mdmTools = FileManagerFactory.getFileManager(UploadService.this);
                        name1 = mdmTools.getFileName(fileUrl1);
                        LogUtil.i(LOG, "handler success ready insert database...");
                        Bundle bundle1 = msg.getData();
                        String folderID1 = bundle1.getString("folderID", "0");
                        String fileId1 = bundle1.getString("fileID", "1");
                        String filePath1 = bundle1.getString("filePath", "");
                        
                        FileInfoResponseV2 fileInfoResponse1 = mdmTools.getFileInfo(fileId1,
                            folderID1,
                            filePath1);
                        if (null != fileInfoResponse1)
                        {
                            
                            if (null != shareDriveService)
                            {
                                long result = shareDriveService.insertUploadData(fileInfoResponse1);
                                LogUtil.i(LOG, "handler success finish insert database...");
                            }
                        }
                        //
                        boolean isDelete = mdmTools.deleteFile(fileUrl1);
                        if (!isDelete)
                        {
                            LogUtil.e(LOG, "UploadService delete  mdm stream File fail...");
                        }
                    }
                    else
                    {
                        LogUtil.e(LOG, "UploadService upload  mdm stream success handler fileUrl is null...");
                    }
                    Toast.makeText(UploadService.this,
                        "["
                            + name1
                            + "]"
                            + UploadService.this.getResources()
                                .getString(R.string.fileListadapter_upload_success),
                        Toast.LENGTH_SHORT).show();
                    break;
                case 4:
                    Toast.makeText(UploadService.this,
                        UploadService.this.getResources().getString(R.string.fileListadapter_upload_failed),
                        Toast.LENGTH_SHORT).show();
                    break;
                case 1003:// file upload success
                    iFileManager mdmTools = FileManagerFactory.getFileManager(UploadService.this);
                    Bundle bundle2 = msg.getData();
                    String folderID2 = bundle2.getString("folderID", "0");
                    String fileId2 = bundle2.getString("fileID", "1");
                    String filePath2 = bundle2.getString("filePath", "");
                    String name2 = "";
                    FileInfoResponseV2 fileInfoResponse2 = mdmTools.getFileInfo(fileId2, folderID2, filePath2);
                    if (null != fileInfoResponse2)
                    {
                        name2 = fileInfoResponse2.getName();
                        if (null != shareDriveService)
                        {
                            long result = shareDriveService.insertUploadData(fileInfoResponse2);
                            LogUtil.i(LOG, "handler success finish insert database...");
                        }
                    }
                    Toast.makeText(UploadService.this,
                        "["
                            + name2
                            + "]"
                            + UploadService.this.getResources()
                                .getString(R.string.fileListadapter_upload_success),
                        Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };
    
    private FolderSearchRequestV2 srequest;
    
    private FolderListResponseV2 folderResponse;
    
    @Override
    public void onDestroy()
    {
        LogUtil.i(LOG, "onDestroy()...");
        if (null != serviceConnection)
        {
            unbindService(serviceConnection);
        }
        super.onDestroy();
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        LogUtil.i(LOG, "onStartCommand()...");
        return super.onStartCommand(intent, flags, startId);
    }
    
    @Override
    protected void onHandleIntent(Intent intent)
    {
        // TODO Auto-generated method stub
        LogUtil.i(LOG, "onHandleIntent()...");
        // TODO pop notifacation
        bundle = intent.getExtras();
        if (null == shareDriveService)
        {
            LogUtil.i(LOG, "onHandleIntent shareDriveService is null that need to bind service...");
            Intent bindIntent = new Intent(UploadService.this, CloudDriveService.class);
            if (null != serviceConnection)
            {
                LogUtil.i(LOG, "onHandleIntent serviceConnection has value start bind service...");
                bindService(bindIntent, serviceConnection, Context.BIND_AUTO_CREATE);
            }
            else
            {
                LogUtil.e(LOG, "onHandleIntent serviceConnection is null bind service fail...");
            }
        }
    }
}
